package dfs.island;

/**
 * @Description 463. 岛屿的周长
 * @Author Firenut
 * @Date 2023-02-10 00:48
 */
public class T463_islandPerimeter {
    // 法2:迭代
    int []dx={0,1,0,-1};
    int []dy={1,0,-1,0};

    public int islandPerimeter1(int[][] grid) {
        int count=0;
        for(int i=0;i<grid.length;i++){
            for(int j=0;j<grid[0].length;j++){
                if(grid[i][j]==1){
                    for(int k=0;k<4;k++){
                        int xx=i+dx[k];
                        int yy=j+dy[k];
                        if(xx<0||xx>=grid.length||yy<0||yy>=grid[0].length||grid[xx][yy]==0){
                            count++;
                        }
                    }
                }
            }
        }
        return count;
    }


//    法1:DFS
    public int islandPerimeter(int[][] grid) {
        for(int i=0;i<grid.length;i++){
            for(int j=0;j<grid[0].length;j++){
                if(grid[i][j]==1){
                    return dfs(grid,i,j);
                }
            }
        }
        return 0;
    }
    int dfs(int[][]grid,int x,int y){
        if(!(x>=0&&y>=0&&x<grid.length&&y<grid[0].length)){
            return 1;
        }

        if(grid[x][y]==0){
            return 1;
        }

        if(grid[x][y]==2){
            return 0;
        }
        grid[x][y]=2;
        return dfs(grid,x-1,y)+dfs(grid,x+1,y)+dfs(grid,x,y-1)+dfs(grid,x,y+1);
    }
}